﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using ByHand.Services.Code;
using ByHand.Services.Implements;
using Newtonsoft.Json.Linq;

namespace BackEnd.Code
{
    [assembly: WebActivator.PreApplicationStartMethod(typeof(AutoUpdate), "Start")]
    public class AutoUpdate
    {
        private static readonly Timer _timer = new Timer(OnTimerElapsed);
        private static readonly JobHost _jobHost = new JobHost();

        public static void Start()
        {
            _timer.Change(TimeSpan.Zero, TimeSpan.FromMinutes(30));
        }

        private static void OnTimerElapsed(object sender)
        {
            _jobHost.DoWork(() =>
            {
                var mIDs = UtilityService.GetAllMerchantID();
                foreach (var item in mIDs)
                {
                    string url = GuuProduct.CreateUrlGetDataUpdate(item, 1, 10000);
                    string data = GuuProduct.Getjsondata(url);
                    var objects = JArray.Parse(data); // parse as array
                    foreach (JObject root in objects)
                    {
                        int guuID = 0;
                        int guustatus = 0;
                        foreach (KeyValuePair<String, JToken> ap in root)
                        {
                            if (ap.Key == "ID") {
                                guuID = Convert.ToInt32((String)ap.Value);
                            }
                            if (ap.Key == "Status")
                            {
                                guustatus = Convert.ToInt32((String)ap.Value);
                            }
                        }
                        UtilityService.UpdateProduct(guuID, guustatus);
                    }
                }
            });
        }
    }
}